<template>
  <view class="page">
    <!--		通知公告浮窗题型-->
    <notificationInfo @unreadMessageCount="(val) => (unreadMessageCount = val)"></notificationInfo>
    <view class="header">
      <view class="row">
        <!--			切换考试-->
        <view class="toggle-test" @click="toggleTest">
          <image :src="switchIcon" class="icon"></image>
          <text v-if="!userSelectExamId">切换考试</text>
          <text v-else>{{ userSelectExamName }}</text>
        </view>
        <!--			距离考试还有n天-->
        <view class="right">
          <view class="count-down" v-if="examRemainingTime >= 0">
            <text class="text">距离考试还有</text>
            <text class="day">{{ examRemainingTime }}</text>
            <text class="text">天</text>
          </view>
          <view class="alert-icon" @click="() => $uni.navigateTo({ url: '/mine/pages/myMessage/list' })">
            <image class="icon" :src="alertIcon">
              <!--						未读消息数量-->
              <view class="unread-message-count" v-if="unreadMessageCount !== 0">{{ unreadMessageCount }}</view>
            </image>
          </view>
        </view>
      </view>
      <!--			今日背单词打卡和查看详情计划-->
      <view class="row">
        <!-- 查看详情组件 -->
        <vocabularyPlanInfo style="width: 100%" :planInfo="planInfo"></vocabularyPlanInfo>
      </view>
    </view>
    <view class="main">
      <!--     轮播图-->
      <view style="border-radius: 20rpx; overflow: hidden">
        <banner :position="1" height="200rpx"></banner>
      </view>
      <!--			应用-->
      <view class="block">
        <appList></appList>
      </view>
      <!--			tab列表-->
      <tabList></tabList>
      <!-- 背单词 -->
      <view class="block">
        <thesaurus-list></thesaurus-list>
      </view>
    </view>

    <popup ref="popup"></popup>
    <embedded-guidelines-musk></embedded-guidelines-musk>
    <studyRoomFloat></studyRoomFloat>
    <customTabbar></customTabbar>
  </view>
</template>

<script>
import store from "../../store"
import request from "../../utils/request"
import { getShowNginxPicUrl, getStaticUrl } from "@/utils/settings"
import switchIcon from "./assets/switch.png"
import { userActionType } from "@/store/modules/user"
import { getShowImage, getSysParam, handleUrlParams, isSimpleApp, valIsEmpty } from "@/utils"
import shareInfo from "../../utils/shareInfo"
import recommender from "../../utils/recommender"
import popup from "../../components/popup/index.vue"
import arrayUtils from "../../utils/arrayUtils"
import vocabularyPlanInfo from "./components/vocabularyPlanInfo.vue"
import topicClassList from "./components/topicClassList.vue"
import thesaurusList from "./components/thesaurusList.vue"
import ArticleList from "./components/articleList.vue"
import { dictActionType } from "@/store/modules/dict"
import { showModal } from "@/utils"
import persistence from "@/store/persistence"
import { appActionType } from "@/store/modules/app"
import dateUtils from "@/utils/dateUtils"
import banner from "@/components/banner.vue"
import websocket from "@/utils/websocket"
import notificationInfo from "./components/notificationInfo/index.vue"
import alertIcon from "./assets/alert.png"
import embeddedGuidelinesMusk from "./components/embeddedGuidelinesMusk.vue"
import studyRoomFloat from "@/components/studyRoomFloat/index.vue"
import customTabbar from "@/components/customTabbar/index.vue"
import { vocabularyLearningActionType } from "@/store/modules/vocabularyLearning"
import appList from "./components/appList.vue"
import tabList from "./components/tabList.vue"

export default {
  computed: {
    //考试剩余天数
    examRemainingTime() {
      if (!this.userSelectExamTime) {
        return 0
      }
      //用户填写了自己的考试时间，且用户自己填写的日期晚于当前日期则取用户所自己填写的考试时间
      let examTime
      if (
        this.userInfo &&
        this.userInfo.personalInfo &&
        this.userInfo.personalInfo.examTime &&
        dateUtils.isDateAfter(new Date(this.userInfo.personalInfo.examTime), new Date())
      ) {
        examTime = this.userInfo.personalInfo.examTime
        //否则取后台配置的考试时间
      } else {
        examTime = this.userSelectExamTime
      }
      const now = new Date().getTime()
      const examTimeDate = new Date(examTime).getTime()
      const remainingTime = examTimeDate - now
      return Math.floor(remainingTime / (24 * 3600 * 1000))
    },
    userSelectExamId: () => store.getters[userActionType.getters.userSelectExamId], // 用户选择的考试id
    userSelectExamName: () => store.getters[userActionType.getters.userSelectExamName], // 用户选择的考试名称
    userSelectExamTime: () => store.getters[userActionType.getters.userSelectExamTime], // 用户选择的考试时间
  },
  components: {
    ArticleList,
    popup,
    vocabularyPlanInfo,
    topicClassList,
    thesaurusList,
    banner,
    notificationInfo,
    embeddedGuidelinesMusk,
    studyRoomFloat,
    customTabbar,
    appList,
    tabList,
  },
  data() {
    return {
      getStaticUrl,
      switchIcon,
      userInfo: null,
      mode: "",
      persistence,
      alertIcon,
      unreadMessageCount: 0, // 未读消息数量
      planInfo: null,
    }
  },
  async onShow() {
    websocket.trackCurrentPage("首页").catch(() => {})
    this.userInfo = await store.dispatch(userActionType.action.userInfo)
    //获取当前的考试信息
    !this.userSelectExamId && (await store.dispatch(userActionType.action.examInfo))
    //获取计划详情
    this.userSelectExamId && (this.planInfo = await store.dispatch(vocabularyLearningActionType.actions.planInfo))
    this.$nextTick(async () => {
      //新用户弹框
      //不是新用户或者已经弹过了直接返回
      //精简版小程序不弹出
      if (!this.userInfo.isNewUser || persistence.newUserWelfareDialog.get() || (await isSimpleApp())) {
        return
      }
      //判断是否是受邀请进来的
      //受邀请进来的
      if (store.getters[userActionType.getters.recommender.id] && (await getSysParam("showInviteUserPopup")) === "是") {
        this.$refs.popup.addPopupItem(
          getShowNginxPicUrl("i6e94Xgg6ZN5gbX9xXsg.png"),
          async () => {
            showModal({
              content: "领取成功",
            })
            persistence.newUserWelfareDialog.set(true)
          },
          () => {
            persistence.newUserWelfareDialog.set(true)
          },
        )
        //不是受邀请进来的
      } else if ((await getSysParam("showNewUserPopup")) === "是") {
        this.$refs.popup.addPopupItem(
          getShowNginxPicUrl("atUNoTZXCvgW4GaeEYXi.png"),
          async () => {
            persistence.newUserWelfareDialog.set(true)
            uni.navigateTo({
              url: handleUrlParams("/pages/imagePage/index", {
                urlList: encodeURIComponent(JSON.stringify([getShowNginxPicUrl("20240316190320.png")])),
                btnText: "领取会员",
                jumpPath: encodeURIComponent(
                  handleUrlParams("/pages/imagePage/index", {
                    urlList: encodeURIComponent(JSON.stringify([getShowNginxPicUrl("2f4f26734cd6ebab9383f2721f1d1ab.jpg")])),
                  }),
                ),
                jumpType: "jumpPage",
              }),
            })
          },
          () => {
            persistence.newUserWelfareDialog.set(true)
          },
        )
      }
    })
  },
  async onLoad() {
    uni.showLoading({
      title: "加载中",
      mask: true,
    })
    //新用户跳欢迎页
    // const userInfo = await store.dispatch(userActionType.action.userInfo)
    // if (userInfo.isNewUser && valIsEmpty(userInfo.personalInfo)) {
    //   uni.navigateTo({
    //     url: "/pages/welcome/index",
    //   })
    // }
  },
  methods: {
    //切换考试
    async toggleTest() {
      uni.navigateTo({ url: "/pages/examSelection/index" })
    },
    getShowImage,
  },
  //右上角分享
  async onShareAppMessage() {
    return await shareInfo.getDefaultShareInfo()
  },
  //页面到达底部触发资讯文章加载下一页
  onReachBottom() {
    this.$refs.articleList && this.$refs.articleList.handleReachBottom()
  },
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: var(--gray-background-color);

  > .header {
    background: url("https://kou.gdzmtech.com/pic/f3GYkkxqMop3MP474B6T.png") no-repeat;
    background-size: 100% 100%;
    padding: {
      left: 30rpx;
      right: 30rpx;
      top: 10rpx;
    }
    .row {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .toggle-test {
        color: var(--text-color);
        font-size: 30rpx;
        display: flex;
        align-items: center;
        background: white;
        height: 60rpx;
        padding: 0 20rpx;
        border-radius: 30rpx;

        .icon {
          width: 30rpx;
          height: 30rpx;
          margin-right: 10rpx;
        }
      }

      .right {
        display: flex;
        align-items: center;
        .count-down {
          color: var(--text-color-white);
          font-size: 30rpx;
          display: flex;
          align-items: center;

          .day {
            font-weight: bold;
            margin: 0 10rpx;
          }
        }
        .alert-icon {
          width: 40rpx;
          height: 40rpx;
          margin-left: 30rpx;
          position: relative;
          .icon {
            width: 100%;
            height: 100%;
          }
          .unread-message-count {
            position: absolute;
            top: -16rpx;
            right: -20rpx;
            width: 38rpx;
            height: 38rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            background: red;
            color: white;
            border-radius: 50%;
            font-size: 25rpx;
          }
        }
      }
    }
  }

  .main {
    background: #fffaf5;
    border-radius: 50rpx 50rpx 0 0;
    position: absolute;
    top: 258rpx;
    z-index: 80;
    left: 0;
    width: 100vw;
    padding: {
      top: 30rpx;
      left: 30rpx;
      right: 30rpx;
      bottom: calc(182rpx + env(safe-area-inset-bottom));
    }
    .block {
      box-sizing: border-box;
      &:not(:first-child) {
        margin-top: 30rpx;
      }
    }
  }
}
</style>
